import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { getUserFromRequest } from '@/lib/auth'
import { downloadVideoFiles } from '@/lib/fileDownloader'
import AliyunSenseVoiceService from '@/lib/aliyunSenseVoice'

// 开始执行任务
export async function POST(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const user = await getUserFromRequest(request)

    if (!user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      )
    }

    const taskId = parseInt(params.id)
    
    if (isNaN(taskId)) {
      return NextResponse.json(
        { error: '无效的任务ID' },
        { status: 400 }
      )
    }

    // 检查任务是否存在
    const task = await prisma.extractionTask.findUnique({
      where: { id: taskId },
      select: {
        id: true,
        name: true,
        keywords: true,
        maxCount: true,
        status: true,
        progress: true,
        totalFound: true,
        extracted: true,
        lastRunAt: true,
        nextRunAt: true,
        isRecurring: true,
        interval: true,
        autoDownloadFiles: true,
        autoExtractText: true,
        createdBy: true,
        createdAt: true,
        updatedAt: true
      }
    })

    if (!task) {
      return NextResponse.json(
        { error: '任务不存在' },
        { status: 404 }
      )
    }

    // 检查任务状态
    if (task.status === 'running') {
      return NextResponse.json(
        { error: '任务已在运行中' },
        { status: 400 }
      )
    }

    // 更新任务状态为运行中
    const updatedTask = await prisma.extractionTask.update({
      where: { id: taskId },
      data: {
        status: 'running',
        progress: 0,
        lastRunAt: new Date()
      }
    })

    // 创建执行记录
    const execution = await prisma.taskExecution.create({
      data: {
        taskId: taskId,
        status: 'running',
        startedAt: new Date()
      }
    })

    // 异步执行任务（这里是模拟实现）
    executeTaskAsync(taskId, execution.id)

    return NextResponse.json({
      message: '任务已开始执行',
      task: updatedTask,
      execution
    })

  } catch (error) {
    console.error('Start task error:', error)
    return NextResponse.json(
      { error: '启动任务失败' },
      { status: 500 }
    )
  }
}

// 异步执行任务的实现 - 集成TikHub API
async function executeTaskAsync(taskId: number, executionId: number) {
  try {
    // 获取任务信息
    const task = await prisma.extractionTask.findUnique({
      where: { id: taskId }
    })

    if (!task) return

    const keywords = JSON.parse(task.keywords)
    let totalFound = 0
    let extracted = 0
    let logs = `开始执行任务: ${task.name}\n关键词: ${keywords.join(', ')}\n`

    // 为每个关键词执行搜索
    for (let i = 0; i < keywords.length; i++) {
      const keyword = keywords[i]
      logs += `\n正在搜索关键词: ${keyword}\n`

      try {
        // 调用TikHub API搜索视频
        const searchResults = await searchTikTokVideos(keyword, Math.ceil(task.maxCount / keywords.length))

        if (searchResults && searchResults.length > 0) {
          totalFound += searchResults.length

          // 保存视频数据到数据库
          for (const videoData of searchResults) {
            try {
              const savedVideo = await saveVideoToDatabase(videoData, task.keywords)
              extracted++
              logs += `✓ 保存视频: ${videoData.aweme_id}\n`

              // 自动下载文件（如果启用）
              if (task.autoDownloadFiles) {
                try {
                  logs += `开始下载文件: ${videoData.aweme_id}\n`
                  const downloadResult = await downloadVideoFiles(savedVideo.id)
                  if (downloadResult.success) {
                    logs += `✓ 文件下载完成: ${videoData.aweme_id}\n`

                    // 自动提取文案（如果启用且下载成功）
                    if (task.autoExtractText) {
                      try {
                        logs += `开始自动提取文案: ${videoData.aweme_id}\n`
                        const extractResult = await autoExtractText(savedVideo.id, savedVideo.audioUrl || undefined)
                        if (extractResult.success) {
                          logs += `✓ 文案提取完成: ${videoData.aweme_id}\n`
                        } else {
                          logs += `✗ 文案提取失败: ${videoData.aweme_id} - ${extractResult.error}\n`
                        }
                      } catch (extractError) {
                        console.error('Auto extract text error:', extractError)
                        logs += `✗ 文案提取异常: ${videoData.aweme_id} - ${extractError instanceof Error ? extractError.message : '未知错误'}\n`
                      }
                    }
                  } else {
                    logs += `✗ 文件下载失败: ${videoData.aweme_id} - ${downloadResult.error}\n`
                  }
                } catch (downloadError) {
                  console.error('Auto download error:', downloadError)
                  logs += `✗ 文件下载异常: ${videoData.aweme_id} - ${downloadError instanceof Error ? downloadError.message : '未知错误'}\n`
                }
              }
            } catch (saveError) {
              logs += `✗ 保存视频失败: ${videoData.aweme_id} - ${saveError}\n`
            }
          }
        } else {
          logs += `未找到相关视频\n`
        }

        // 更新进度
        const progress = Math.floor(((i + 1) / keywords.length) * 100)

        await prisma.extractionTask.update({
          where: { id: taskId },
          data: {
            progress,
            totalFound,
            extracted
          }
        })

        // 更新执行记录的日志
        await prisma.taskExecution.update({
          where: { id: executionId },
          data: {
            videosFound: totalFound,
            videosExtracted: extracted,
            logs
          }
        })

        // 检查任务是否被停止
        const currentTask = await prisma.extractionTask.findUnique({
          where: { id: taskId }
        })

        if (currentTask?.status !== 'running') {
          logs += `任务被手动停止\n`
          break
        }

        // 避免API限制，添加延迟
        if (i < keywords.length - 1) {
          await new Promise(resolve => setTimeout(resolve, 1000))
        }

      } catch (apiError) {
        logs += `✗ 搜索关键词 "${keyword}" 失败: ${apiError}\n`
        console.error(`Search error for keyword "${keyword}":`, apiError)
      }
    }

    logs += `\n任务执行完成！\n总计找到: ${totalFound} 个视频\n成功提取: ${extracted} 个视频`

    // 完成任务
    await prisma.extractionTask.update({
      where: { id: taskId },
      data: {
        status: 'completed',
        progress: 100,
        nextRunAt: task.isRecurring
          ? new Date(Date.now() + (task.interval || 24) * 60 * 60 * 1000)
          : null
      }
    })

    // 更新执行记录
    await prisma.taskExecution.update({
      where: { id: executionId },
      data: {
        status: 'completed',
        completedAt: new Date(),
        videosFound: totalFound,
        videosExtracted: extracted,
        logs
      }
    })

  } catch (error) {
    console.error('Execute task error:', error)

    const errorMessage = error instanceof Error ? error.message : '未知错误'

    // 更新任务状态为失败
    await prisma.extractionTask.update({
      where: { id: taskId },
      data: {
        status: 'failed',
        progress: 0
      }
    })

    // 更新执行记录
    await prisma.taskExecution.update({
      where: { id: executionId },
      data: {
        status: 'failed',
        completedAt: new Date(),
        errorMessage,
        logs: (await prisma.taskExecution.findUnique({ where: { id: executionId } }))?.logs + `\n任务执行失败: ${errorMessage}`
      }
    })
  }
}

// 调用TikHub API搜索TikTok视频
async function searchTikTokVideos(keyword: string, count: number = 10) {
  const API_KEY = process.env.TIKHUB_API_KEY || '9r8Ie1BX3l8NgQlSwFe1m3A/8gA7zaXbi5R232rau1Ny1VMqUeZN1x65Ng=='

  // 构建查询参数
  const params = new URLSearchParams({
    keyword: keyword,
    offset: '0',
    count: count.toString(),
    sort_type: '0', // 0-相关度，1-最多点赞
    publish_time: '0' // 0-不限制，1-最近一天，7-最近一周，30-最近一个月，90-最近三个月，180-最近半年
  })

  const TIKHUB_API_URL = `https://api.tikhub.io/api/v1/tiktok/app/v3/fetch_general_search_result?${params}`

  try {
    console.log('调用TikHub API:', { keyword, count, url: TIKHUB_API_URL.replace(API_KEY, 'xxx') })

    const response = await fetch(TIKHUB_API_URL, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${API_KEY}`,
        'Accept': 'application/json'
      }
    })

    console.log('TikHub API响应状态:', response.status)

    if (!response.ok) {
      const errorText = await response.text()
      console.error('TikHub API错误响应:', errorText)
      throw new Error(`TikHub API error: ${response.status} ${response.statusText} - ${errorText}`)
    }

    const result = await response.json()
    console.log('TikHub API响应:', {
      code: result.code,
      dataLength: result.data?.data?.length || 0
    })

    if (result.code === 200 && result.data && result.data.data) {
      return result.data.data.map((item: any) => item.aweme_info).filter(Boolean)
    } else {
      throw new Error(`TikHub API returned error: ${result.message || 'Unknown error'}`)
    }
  } catch (error) {
    console.error('TikHub API call failed:', error)
    throw error
  }
}

// 自动提取文案函数 - 直接使用阿里云百炼服务
async function autoExtractText(videoId: number, audioUrl?: string): Promise<{success: boolean, error?: string}> {
  try {
    // 获取视频信息
    const video = await prisma.tikTokVideo.findUnique({
      where: { id: videoId }
    })

    if (!video) {
      return { success: false, error: '视频不存在' }
    }

    if (audioUrl) {
      // 有音频，使用阿里云SenseVoice语音识别
      console.log(`开始语音识别，视频ID: ${videoId}, 音频URL: ${audioUrl}`)

      // 检查是否已经有识别记录
      const existingExtraction = await prisma.textExtraction.findFirst({
        where: {
          videoId: videoId,
          method: 'aliyun_sensevoice',
          status: 'completed'
        }
      })

      if (existingExtraction) {
        console.log(`视频 ${videoId} 已有语音识别结果，跳过`)
        return { success: true, error: '已有识别结果' }
      }

      // 创建识别任务记录
      const extraction = await prisma.textExtraction.create({
        data: {
          videoId: videoId,
          method: 'aliyun_sensevoice',
          status: 'processing',
          extractedText: '',
          confidence: 0
        }
      })

      try {
        // 初始化阿里云SenseVoice服务
        const senseVoiceService = new AliyunSenseVoiceService()

        // 执行语音识别
        const results = await senseVoiceService.transcribeAudio(
          [audioUrl],
          ['auto'], // 自动检测语言
          true // 过滤语气词
        )

        const result = results[0]

        if (result.success && result.cleanText) {
          // 更新识别结果
          await prisma.textExtraction.update({
            where: { id: extraction.id },
            data: {
              status: 'completed',
              extractedText: result.cleanText,
              confidence: 0.95,
              language: senseVoiceService.detectLanguage(result.cleanText || '')
            }
          })

          console.log(`语音识别成功，视频ID: ${videoId}`)
          return { success: true }
        } else {
          // 识别失败
          await prisma.textExtraction.update({
            where: { id: extraction.id },
            data: {
              status: 'failed'
            }
          })

          console.log(`语音识别失败，视频ID: ${videoId}, 错误: ${result.error}`)
          return { success: false, error: result.error || '语音识别失败' }
        }
      } catch (serviceError) {
        // 更新为失败状态
        await prisma.textExtraction.update({
          where: { id: extraction.id },
          data: {
            status: 'failed'
          }
        })

        console.error(`语音识别服务异常，视频ID: ${videoId}`, serviceError)
        return {
          success: false,
          error: serviceError instanceof Error ? serviceError.message : '语音识别服务异常'
        }
      }
    } else {
      // 无音频，使用OCR（这里暂时跳过，因为需要实现OCR服务）
      console.log(`视频 ${videoId} 无音频，跳过OCR提取`)
      return { success: false, error: '无音频文件，OCR功能待实现' }
    }
  } catch (error) {
    console.error(`自动提取文案异常，视频ID: ${videoId}`, error)
    return {
      success: false,
      error: error instanceof Error ? error.message : '未知错误'
    }
  }
}

// 保存视频数据到数据库
async function saveVideoToDatabase(videoData: any, taskKeywords: string) {
  try {
    // 提取视频基本信息
    const awemeId = videoData.aweme_id
    const desc = videoData.desc || ''
    const publishTime = videoData.create_time ? new Date(videoData.create_time * 1000) : new Date()

    // 提取作者信息
    const author = videoData.author || {}
    const authorNickname = author.nickname || author.unique_id || 'Unknown'
    const authorId = author.uid || author.sec_uid || ''
    const authorFollowers = author.follower_count || 0
    const authorFollowing = author.following_count || 0

    // 提取统计信息
    const statistics = videoData.statistics || {}
    const likes = statistics.digg_count || 0
    const shares = statistics.share_count || 0
    const comments = statistics.comment_count || 0
    const views = statistics.play_count || 0

    // 提取视频信息
    const video = videoData.video || {}
    const duration = video.duration ? Math.floor(video.duration / 1000) : 0

    // 提取视频URL - 优先选择高质量的视频
    const playAddr = video.play_addr || video.bit_rate?.[0]?.play_addr
    const videoUrl = playAddr?.url_list?.[0] || ''

    // 提取封面图片URL
    const coverUrl = video.cover?.url_list?.[0] || video.origin_cover?.url_list?.[0] || ''

    // 提取音频信息
    const music = videoData.music || {}
    const audioUrl = music.play_url?.url_list?.[0] || ''
    const musicTitle = music.title || ''
    const musicAuthor = music.author || ''

    // 提取话题标签
    const chaList = videoData.cha_list || []
    const hashtags = JSON.stringify(chaList.map((cha: any) => ({
      id: cha.cid,
      name: cha.cha_name,
      desc: cha.desc
    })))

    // 构建TikTok分享URL
    const shareUrl = videoData.share_url || `https://www.tiktok.com/@${author.unique_id}/video/${awemeId}`

    // 检查视频是否已存在
    const existingVideo = await prisma.tikTokVideo.findUnique({
      where: { videoId: awemeId }
    })

    if (existingVideo) {
      // 更新现有视频的统计数据和其他信息
      return await prisma.tikTokVideo.update({
        where: { videoId: awemeId },
        data: {
          likes,
          shares,
          comments,
          views,
          authorFollowers,
          authorFollowing,
          updatedAt: new Date()
        }
      })
    } else {
      // 创建新视频记录
      return await prisma.tikTokVideo.create({
        data: {
          videoId: awemeId,
          url: shareUrl,
          title: desc.length > 100 ? desc.substring(0, 100) + '...' : desc,
          description: desc,
          author: authorNickname,
          authorId: authorId,
          authorFollowers,
          authorFollowing,
          likes,
          shares,
          comments,
          views,
          duration,
          videoUrl: videoUrl,
          audioUrl: audioUrl,
          coverUrl: coverUrl,
          hashtags: hashtags,
          musicTitle: musicTitle,
          musicAuthor: musicAuthor,
          publishTime: publishTime,
          tags: taskKeywords, // 将任务关键词作为标签保存
          createdAt: new Date()
        }
      })
    }
  } catch (error) {
    console.error('Save video to database error:', error)
    throw error
  }
}
